package commMqtt

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Pair"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/periodTask"
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

type autoTask struct {
}

func (e *autoTask) TaskType() periodTask.TaskType {
	return periodTask.TaskShare
}

func (e *autoTask) SchedulePeriod() int64 {
	return 60
}

func (e *autoTask) Execute() {
	keys := mgr.keys()
	for k, _ := range keys {
		client := mgr.getClient(k)
		e.execute(client)
	}
}

func (e *autoTask) execute(client *MqttClient) {
	// 如果没
	if !client.IsConnected() {
		err := client.Connect()
		if err != nil {
			return
		}

	}

	client.topics.Range(func(topic, value interface{}) bool {
		pair := value.(Pair.Pair)

		handler := pair.Key.(mqtt.MessageHandler)
		ok := pair.Value.(bool)

		if ok == true {
			return false
		}

		err := client.subscribe(topic.(string), handler)
		if err != nil {
			return false
		}

		pair.Value = true
		client.topics.Store(topic, pair)
		return true
	})
}
